﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Windows.Media.Animation;
using System.Windows.Media;
using MoMoTransferVN_WP.Framework;
using SQLite;
using MoMoTransferVN_WP.database;
using MoMoTransferVN_WP.utils;
using Microsoft.Phone.UserData;
using System.Windows.Threading;
using com.mservice.momo.msg;

namespace MoMoTransferVN_WP.page
{
    public partial class MainPage : PhoneApplicationPage, App.IMoMoMessageCome
    {
        private SQLiteConnection dbConn;
        List<uint> allPhoneNumber = new List<uint>();
        // creating timer instance
        DispatcherTimer newTimer = new DispatcherTimer() { /* timer interval specified as 300 miliseconds*/Interval = TimeSpan.FromMilliseconds(300) };
        int loop = 0, tick=0;
        private const double _dragDistanceToOpen = 75.0;
        private const double _dragDistanceToClose = 400.0;
        private double _dragDistanceNegative = -75.0;
        private bool _isSettingsOpen = false;
        private FrameworkElement _feContainer;
        public MainPage()
        {
            InitializeComponent();
            _feContainer = this.Container as FrameworkElement;
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            (Application.Current as MoMoTransferVN_WP.App).setCkb((App.IMoMoMessageCome)this);
            
            /// Create the database connection.
            dbConn = new SQLiteConnection(DBHelper.DB_PATH);
            /// Create the table momoContact, if it doesn't exist.
            dbConn.CreateTable<momoContact>();
            //
            if(!SettingUtils.readBool(Assets.KEY_CREATE_DB))
            {
                int i=0;
                SaveAllContact();
                //get all contact and save phone number to a list
                List<momoContact>  retrievedmomoContacts = dbConn.Table<momoContact>().ToList<momoContact>();
                loop = retrievedmomoContacts.Count / 30 + 1;
                foreach (var t in retrievedmomoContacts)
                {
                    allPhoneNumber[i] = (uint)t.phoneNumber;
                    i++;
                }
                if(loop==1)
                {
                    MomoMessage msg = MoMoReq.processIsMoMoer(App.getNextMsgId(), allPhoneNumber);
                    (Application.Current as MoMoTransferVN_WP.App).mMoMoTcpClient.sendMoMoMesage(msg); 
                }
                else
                {                 
                    
                    // Sub-routine OnTimerTick will be called at every 1 second
                    newTimer.Tick += OnTimerTick;
                    newTimer.Start();
                }
                
                SettingUtils.saveSetting(Assets.KEY_CREATE_DB, true);
            }
            
        }
        public void onDisconnectWithError(string error)
        {

        }
        void OnTimerTick(Object sender, EventArgs args)
        {
            if (tick < loop)
            {
                List<uint> childContact = new List<uint>();
                childContact = allPhoneNumber.GetRange(30 * tick, 30);
                MomoMessage msg = MoMoReq.processIsMoMoer(App.getNextMsgId(), childContact);
                (Application.Current as MoMoTransferVN_WP.App).mMoMoTcpClient.sendMoMoMesage(msg); 
                tick++;
            }
            else newTimer.Stop();
                
        }
        void App.IMoMoMessageCome.onMoMoMessageCome(int cmdType, long cmdIndex, byte[] cmdBody)
        {
            if (cmdType == (int)MsgType.WHO_IS_MOMOER_REPLY)
            {
                WhoIsMomoer momoer = WhoIsMomoer.CreateBuilder().MergeFrom(cmdBody).Build();
                foreach(var t in momoer.NumbersList)
                {

                }
                
            }
        }
        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            if (dbConn != null)
            {
                /// Close the database connection.
                dbConn.Close();
            }
        }

        public void SaveAllContact()
        {
            Contacts objContacts = new Contacts();

            objContacts.SearchCompleted += new EventHandler<ContactsSearchEventArgs>(objContacts_SearchCompleted);

            objContacts.SearchAsync(string.Empty, FilterKind.None, null);
        }
        private void objContacts_SearchCompleted(object sender, ContactsSearchEventArgs e)
        {
            int tmp = 0;
            foreach (Contact con in e.Results)
            {
                tmp = DBHelper.phoneSucessful(con.PhoneNumbers.FirstOrDefault().PhoneNumber);
                if (tmp != 0) //kiem tra neu so phone hop le thi moi insert vao db
                {
                    //create a new momo contact
                    momoContact momoer = new momoContact()
                    {
                        name = con.DisplayName,
                        phoneNumber = tmp,
                        photoUrl = "Assets/Images/ContactPhoto.png",
                        IsMomoer = false
                    };

                    /// Insert the new momoer in the Momoer table.
                    dbConn.Insert(momoer);
                }
            }
        }

        private void CloseSettings()
        {
            var trans = _feContainer.GetHorizontalOffset().Transform;
            trans.Animate(trans.X, 0, TranslateTransform.XProperty, 300, 0, new CubicEase
            {
                EasingMode = EasingMode.EaseOut
            });

            _isSettingsOpen = false;
        }

        private void OpenSettings()
        {
            var trans = _feContainer.GetHorizontalOffset().Transform;
            trans.Animate(trans.X, 400, TranslateTransform.XProperty, 300, 0, new CubicEase
            {
                EasingMode = EasingMode.EaseOut
            });

            _isSettingsOpen = true;
        }
        private void GestureListener_OnDragDelta(object sender, DragDeltaGestureEventArgs e)
        {
            if (e.Direction == System.Windows.Controls.Orientation.Horizontal && e.HorizontalChange > 0 && !_isSettingsOpen)
            {
                double offset = _feContainer.GetHorizontalOffset().Value + e.HorizontalChange;
                if (offset > _dragDistanceToOpen)
                    this.OpenSettings();
                else
                    _feContainer.SetHorizontalOffset(offset);
            }

            if (e.Direction == System.Windows.Controls.Orientation.Horizontal && e.HorizontalChange < 0 && _isSettingsOpen)
            {
                double offsetContainer = _feContainer.GetHorizontalOffset().Value + e.HorizontalChange;
                if (offsetContainer < _dragDistanceToClose)
                    this.CloseSettings();
                else
                    _feContainer.SetHorizontalOffset(offsetContainer);
            }
        }

        private void GestureListener_OnDragCompleted(object sender, DragCompletedGestureEventArgs e)
        {
            if (e.Direction == System.Windows.Controls.Orientation.Horizontal && e.HorizontalChange > 0 && !_isSettingsOpen)
            {
                if (e.HorizontalChange < _dragDistanceToOpen)
                    this.ResetLayoutRoot();
                else
                    this.OpenSettings();
            }

            if (e.Direction == System.Windows.Controls.Orientation.Horizontal && e.HorizontalChange < 0 && _isSettingsOpen)
            {
                if (e.HorizontalChange > _dragDistanceNegative)
                    this.ResetLayoutRoot();
                else
                    this.CloseSettings();
            }
        }
        private void SettingsStateGroup_CurrentStateChanged(object sender, VisualStateChangedEventArgs e)
        {
            ResetLayoutRoot();
        }
        private void ResetLayoutRoot()
        {
            if (!_isSettingsOpen)
                _feContainer.SetHorizontalOffset(0.0);
            else
                _feContainer.SetHorizontalOffset(400.0);
        }
    }
}